package top.likeqc.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;
import top.likeqc.common.lang.Const;
import top.likeqc.common.lang.Result;
import top.likeqc.entity.SysUser;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Principal;

@Slf4j
@RestController
@CrossOrigin
public class AuthController extends BaseController {

    @Autowired Producer producer;
    
    @CrossOrigin
    @GetMapping("/captcha")
    public Result captcha() throws IOException {
        String key = UUID.randomUUID().toString();
        String code = producer.createText();
        
        // 测试写死
        key = "aaaaa";
        code = "11111";

        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        ImageIO.write(image, "jpg", outputStream);

        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpg;base64,";

        String base64Img = str + encoder.encode(outputStream.toByteArray());
        // 存储到 redis
        redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);
        log.info("验证码 -- {} - {}", key, code);
        return Result.success(
                MapUtil.builder()
                        .put("token", key)
                        .put("captchaImg", base64Img)
                        .build());
    }
    
    @GetMapping("/sys/userInfo")
    public Result userInfo(Principal principal) {
        SysUser sysUser = sysUserService.getByUsername(principal.getName());

        return Result.success(
                MapUtil.builder()
                        .put("id", sysUser.getId())
                        .put("username", sysUser.getUsername())
                        .put("avatar", sysUser.getAvatar())
                        .put("created", sysUser.getCreated())
                        .map());
    }

}
